package com.hobbit.ui.managers
{
	import com.hobbit.ui.components.ComponentLib;
	import com.hobbit.ui.data.UiComponentData;
	import com.hobbit.ui.data.UiLayoutData;
	import com.hobbit.utils.ClassUtil;
	
	import feathers.controls.Button;
	import feathers.controls.TextInput;
	import feathers.display.Image;
	
	import flash.utils.Dictionary;

	/**
	 * Ui素材管理器 提供素材位置格式等 
	 * @author 晓晔
	 * 
	 */
	public class UiManager
	{
		
		public function UiManager()
		{
			if(_instance == null)
			{
				_instance = this;
				viewDataDic = new Dictionary();
			}else
			{
				throw new Error("实例化单例类出错---> UiManager");
			}
			
		}
		private static var _instance:UiManager;
		public static function getInstance():UiManager
		{
			if(_instance == null)
			{
				_instance = new UiManager();
			}
			return _instance;
		}
		
		/**
		 * 数据源字典 -->存入 UiLayoutData 
		 */
		private var viewDataDic:Dictionary;
				
		/**
		 * 存入字典 
		 * @param $viewName
		 * 
		 */
		public function saveData($viewName:String,$uiLayoutData:UiLayoutData):void
		{
			if(viewDataDic[$viewName])
			{
				throw new Error("panelName重复---> UiManager");
			}else
			{
				viewDataDic[$viewName] = $uiLayoutData;
			}
		}
		
		/**
		 * 通过面板名 获取 UiLayoutData
		 * @param $key 面板名
		 * @return 
		 * 
		 */
		public function getData($viewName:String):UiLayoutData
		{
			if(viewDataDic[$viewName])
			{
				return viewDataDic[$viewName];
			}else
			{
				throw new Error("没有此面板信息："+ $viewName);
				return null;
			}
		}
		
		
		/**
		 * 给各view赋值
		 * @param $view 需要赋值的view
		 * @return 
		 * 
		 */
		public function layoutView($view:Object):*
		{
			var className:String = ClassUtil.getClassName($view);
			var layoutData:UiLayoutData = UiManager.getInstance().getData(className);
			for (var name:String in layoutData.compDic)
			{
				var uiComponentData:UiComponentData = layoutData.compDic[name] as UiComponentData;
				var type:String = uiComponentData.type;
				var component:*;
				switch(type)
				{
					case ComponentLib.Button:
						component = new Button();
						break;
					case ComponentLib.TextInput:
						component = new TextInput();
						break;
					case ComponentLib.Image:
						component = new Image(null);
						break;
					default:
						return null;
						break;
					
				}
				$view.addChild(component);
				$view.layoutData = layoutData;
				for(var argument:String in uiComponentData)
				component[argument] = uiComponentData[argument];
			}
			return $view;
			
		}
		
	}
}
